//###############
//FILE : RemoveCommand.java
//WRITER : Daniel Lowengrub, daniel_i_l, 320687098
//EXERCISE : oop ex3 2011
//DESCRIPTION:
//See below
//###############
package oop.ex3.filemanager;

import java.util.ArrayList;

import oop.ex3.communication.SocketAddress;

/**
 * Implements the REMOVE command as specified in the assignment.
 * @author daniel
 */
public class RemoveCommand extends ModifyingCommand {
    private static final String REMOVE_COMMAND = "REMOVE";
    private static final String ABSENT_ERROR = "It is impossible to delete an absent file";
    private static final String END_MSG = "Removing Done";
    private static final String REMOVE_ERROR = "remove failed";
    private static final int FILENAME_ARG = 1;

    /**
     * Construct a remove command with a connection used for communication with
     * NS.
     * @param connection The connection to use.
     */
    public RemoveCommand(NameServerConnection connection) {
        super(REMOVE_COMMAND, connection);
    }

    @Override
    public boolean executeCommand(String command) {
        String fileName = command.split(COMMAND_SPACER)[FILENAME_ARG];

        //remove the file from the database
        if (!_fileDatabase.hasFile(fileName)) {
            System.out.println(ABSENT_ERROR);
            return true;
        }

        //close upload permissions for this file
        _fileDatabase.setStreamingPermission(fileName, false);
        //and wait for uploads to finish
        waitForUploads(fileName);

        if (!_fileDatabase.removeFile(fileName)) {
            System.out.println(REMOVE_ERROR);
            return true;
        }


        //notify nameservers
        ArrayList<SocketAddress> nameServers = _nameServers.getAddressList();
        for (SocketAddress nameServer : nameServers)
            notifyNameServerRemoval(nameServer, fileName);

        System.out.println(END_MSG);
        return true;
    }
}
